package com.tang.script.extrator;

import com.tang.script.command.AbstractScriptCommand;
import com.tang.script.variable.Constant;
import com.tang.script.variable.VariablesType;

import java.util.LinkedList;
import java.util.Map;

/*
 * []里面表示的是常量
 * 常量的表示是: [value:type:title]
 * 例如: [111:string:用户] 表示用户的id是111, 并且类型的stirng
 * */
public class ConstantsExtractor {
    private static final ConstantsExtractor constantsExtractor = new ConstantsExtractor();

    public static ConstantsExtractor get() {
        return constantsExtractor;
    }

    public void extracte(AbstractScriptCommand command) {
        String resolvedScriptText = command.getResolvedScriptText();
        Map constants = command.getConstants();
        StringBuilder stringBuilder = new StringBuilder();
        char[] chars = resolvedScriptText.toCharArray();
        int count = 0;
        for (int i = 0; i < chars.length; i++) {
            while (i < chars.length && chars[i] != '[') {
                stringBuilder.append(chars[i]);
                i++;
            }
            i++;
            StringBuilder temp = new StringBuilder();
            while (i < chars.length && chars[i] != ']') {
                temp.append(chars[i]);
                i++;
            }
            if (temp.length() > 0) {
                int start = temp.length();
                String constName = "const_" + count++;
                Constant constant = resolveConstByString(temp.toString(), constName);
                constants.put(constName, constant);
                stringBuilder.append(constName + " ");
                int end = temp.length();
                constant.setPosition(start, end);
            }
        }
        command.setResolvedScriptText(stringBuilder.toString());
    }

    private Constant resolveConstByString(String str, String constName) {
        String[] split = str.split(":");
        Constant flowConstant = new Constant();
        int index = this.findTypeIndex(split, str);
        flowConstant.setType(VariablesType.valueOf(split[index]));
        flowConstant.setValue(getStringJoin(split, 0, index));
        flowConstant.setTitle(getStringJoin(split, index + 1, split.length));
        flowConstant.setConstName(constName);
        return flowConstant;
    }

    private String getStringJoin(String[] strings, int start, int end) {
        LinkedList<String> res = new LinkedList<>();
        while (start < end) res.add(strings[start++]);
        return String.join(":", res);
    }

    private int findTypeIndex(String[] split, String str) {
        for (int i = 0; i < split.length; i++) {
            for (VariablesType value : VariablesType.values()) {
                if (value.name().equals(split[i])) {
                    return i;
                }
            }
        }
        throw new RuntimeException("不支持的类型: " + str);
    }
}
